<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
        v-show="!props.isReadonly"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="生产线"
              prop="processEquipCode"
              style="width: 100%"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.processEquipCode"
                placeholder=""
                clearable
                disabled
              />
              <span v-else>{{ formData.processEquipCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="equipName" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.equipName"
                placeholder=""
                clearable
                disabled
              />
              <span v-else>{{ formData.equipName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警编号" prop="alarmCode" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.alarmCode"
                placeholder="请输入报警编号"
                clearable
              />
              <span v-else>{{ formData.alarmCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警名称" prop="alarmName" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.alarmName"
                placeholder="请输入报警名称"
                clearable
              />
              <span v-else>{{ formData.alarmName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="报警等级"
              prop="alarmLevel"
              style="width: 100%"
            >
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.alarmLevel"
                clearable
                placeholder="请选择报警等级"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'ScaAlarmLevel'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                dictionaryStore.filterDictName(
                  "ScaAlarmLevel",
                  formData.alarmLevel
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="运行参数"
              prop="parameterName"
              style="width: 100%"
            >
              <el-select
                v-model="formData.parameterName"
                placeholder="请选择运行参数"
                clearable
                filterable
                @change="processParameterChange"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in collectParamList"
                  :key="index"
                  :label="item.parameterDesc"
                  :value="item.parameterName"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
              label="报警内容"
              prop="alarmContent"
              style="width: 100%"
            >
              <el-input
                type="textarea"
                v-if="!props.isReadonly"
                v-model="formData.alarmContent"
                placeholder="请输入报警内容"
                clearable
              />
              <span v-else>{{ formData.alarmContent }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks" style="width: 100%">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.remarks"
                placeholder="请输入备注"
                clearable
              />
              <span v-else>{{ formData.remarks }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用状态" prop="enabled" style="width: 100%">
              <el-radio-group
                v-if="!props.isReadonly"
                v-model="formData.enabled"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.enabled === 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生成工单" prop="isOrder" style="width: 100%">
              <el-radio-group
                v-if="!props.isReadonly"
                v-model="formData.isOrder"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.isOrder === 1 ? "是" : "否" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发送邮件" prop="isMail" style="width: 100%">
              <el-radio-group
                v-if="!props.isReadonly"
                v-model="formData.isMail"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.isMail === 1 ? "是" : "否" }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
          "
        >
          <h4 class="mb-[0px] mt-[0px]">报警模板数据</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="250"
            border
          >
            <el-table-column label="参数" props="parameterName" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.parameterName'"
                  :rules="rules.sonparameterName"
                  label-width="0"
                >
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="row.parameterName"
                    clearable
                    placeholder="请输入参数"
                    style="width: 100%"
                    @change="(e) => changeSonParameterName(e, $index)"
                  >
                    <el-option
                      v-for="item in collectList"
                      :key="`${item.id}`"
                      :label="`${item.parameterDesc}`"
                      :value="`${item.parameterName}`"
                    />
                  </el-select>
                  <span v-else>{{ row.parameterName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="条件"
              props="conditionValue"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.conditionValue'"
                  :rules="rules.soncondition"
                  label-width="0"
                >
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="row.conditionValue"
                    clearable
                    placeholder="请选择报警条件"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList(
                        'ScaAlarmConditions'
                      )"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <span v-else>{{
                    dictionaryStore.filterDictName(
                      "ScaAlarmConditions",
                      row.conditionValue
                    )
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="报警值" props="alarmValue" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.alarmValue'"
                  :rules="rules.sonalarmValue"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.alarmValue"
                    placeholder="请输入报警值"
                    clearable
                  />
                  <span v-else>{{ row.alarmValue }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <el-descriptions
        class="margin-top"
        title=""
        :column="3"
        border
        v-show="props.isReadonly"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">生产线</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.processEquipCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.equipName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警编号</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.alarmCode }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.alarmName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">报警等级</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{
              dictionaryStore.filterDictName(
                "ScaAlarmLevel",
                formData.alarmLevel
              )
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">运行参数</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.parameterDesc }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item :span="3">
          <template #label>
            <div class="cell-item">报警内容</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.alarmContent }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item :span="3">
          <template #label>
            <div class="cell-item">备注</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData?.remarks || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">启用状态</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <el-tag v-show="formData.enabled == 1" type="success">启用</el-tag>
            <el-tag v-show="formData.enabled != 1" type="info">停用</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">生成工单</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <el-tag v-show="formData.isOrder == 1" type="success">是</el-tag>
            <el-tag v-show="formData.isOrder != 1" type="info">否</el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">发送邮件</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            <el-tag v-show="formData.isMail == 1" type="success">是</el-tag>
            <el-tag v-show="formData.isMail != 1" type="info">否</el-tag>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <h4 class="mb-[15px] mt-[20px]" v-show="props.isReadonly">
        报警模板数据
      </h4>
      <div class="formTable3">
        <el-table
          :data="formData.details"
          style="width: 100%"
          :key="Math.random"
          v-show="props.isReadonly"
          max-height="calc(100vh - 260px - 200px)"
          border
        >
          <el-table-column
            props="parameterName"
            label="参数"
            align="center"
            min-width="150"
          >
            <template #default="{ $index, row }">
              <span>{{ row.parameterDesc }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="条件"
            align="center"
            props="conditionValue"
            min-width="170"
          >
            <template #default="{ $index, row }">
              <span>{{
                dictionaryStore.filterDictName(
                  "ScaAlarmConditions",
                  row.conditionValue
                )
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="报警值"
            props="alarmValue"
            min-width="150"
            align="right"
          >
            <template #default="{ $index, row }">
              {{ row.alarmValue }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useRoute } from "vue-router";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "DeviceAlarmSettingsedit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const route = useRoute();
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  equipName: {
    type: String,
    default: () => {
      return "";
    },
  },
  equipCode: {
    type: String,
    default: () => {
      return "";
    },
  },
  equipId: {
    type: String,
    default: () => {
      return "";
    },
  },
  processEquipCode: {
    type: String,
    default: () => {
      return "";
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    formData.equipName = props.equipName;
    formData.processEquipCode = props.processEquipCode;

    getCollectParamList();

    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 获取运行参数
const collectParamList = ref(<any>[]);
async function getCollectParamList(id?: string) {
  const res: any = await request({
    url: "/iotadmin/scaequipcollectionparam/getRunParamList",
    method: "post",
    data: {
      equipCode: props.equipCode,
      relationIds: [route.query.id],
    },
  });
  if (res.code === 200) {
    collectParamList.value = res.data || [];
  }
}
function processParameterChange(name: string) {
  if (name) {
    const current: any =
      collectParamList.value?.filter((e: any) => e.parameterName === name)[0] ??
      {};
    formData.parameterDesc = current.parameterDesc || "";
  } else {
    formData.parameterDesc = "";
  }
}

function changeSonParameterName(name: string, index: number) {
  if (name) {
    const current: any =
      collectList.value?.filter((e: any) => e.parameterName === name)[0] ?? {};
    formData.details[index].parameterDesc = current.parameterDesc || "";
  } else {
    formData.details[index].parameterDesc = "";
  }
}

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  version: "",
  alarmCode: "",
  alarmName: "",
  parameterName: "",
  parameterDesc: "",
  alarmLevel: "",
  typeCode: "",
  typeId: "",
  typeName: "",
  relationId: "",
  relationType: "",
  sustainedTime: "0",
  intervalTime: "0",
  alarmContent: "",
  enabled: 1,
  isOrder: 1,
  isMail: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  equipName: "",
  processEquipCode: "",
  details: [
    {
      id: "",
      version: "",
      alarmId: "",
      alarmCode: "",
      alarmName: "",
      parameterName: "",
      condition: "",
      alarmValue: "",
      calculate: "",
      isEmpty: "",
      enabled: "",
      deleted: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
    },
  ],
});

/** rules规则 */
const rules: any = reactive({
  alarmCode: [{ required: true, message: "请输入报警编号", trigger: "blur" }],
  alarmName: [{ required: true, message: "请输入报警名称", trigger: "blur" }],
  parameterName: [
    { required: false, message: "请选择运行参数", trigger: "change" },
  ],
  alarmLevel: [
    { required: true, message: "请选择报警等级", trigger: "change" },
  ],
  //typeId: [{ required: true, message: "请选择消息列表", trigger: "change" }],
  alarmContent: [
    { required: true, message: "请输入报警内容", trigger: "blur" },
  ],
  relationId: [
    { required: true, message: "请选择设备类型", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonalarmCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonalarmName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonparameterName: [
    { required: true, message: "请输入参数", trigger: "blur" },
  ],
  soncondition: [
    { required: true, message: "请选择报警条件", trigger: "change" },
  ],
  sonalarmValue: [{ required: true, message: "请输入报警值", trigger: "blur" }],
  soncalculate: [
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sustainedTime: [
    {
      required: true,
      message: "请输入数字",
      trigger: "blur",
      validator: validator,
    },
  ],
  intervalTime: [
    {
      required: true,
      message: "请输入数字",
      trigger: "blur",
      validator: validator,
    },
  ],
});

function validator(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过
    callback(new Error("请输入数字"));
  } else {
    if (/(^[0-9]\d*$)/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入数字"));
    }
  }
}

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  alarmId: "",
  alarmCode: "",
  alarmName: "",
  parameterName: "",
  parameterDesc: "",
  conditionValue: "",
  alarmValue: "",
  calculate: "",
  isEmpty: "",
  enabled: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
      formData.intervalTime = String(formData.intervalTime);
      formData.sustainedTime = String(formData.sustainedTime);

      formData.equipName = props.equipName;
      formData.processEquipCode = props.processEquipCode;
    }
  }
);
watch(
  () => props.equipName,
  (newVal: any) => {
    formData.equipName = newVal;
  }
);
watch(
  () => props.processEquipCode,
  (newVal: any) => {
    formData.processEquipCode = newVal;
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.alarmCode = "";
  formData.alarmName = "";
  formData.parameterName = "";
  formData.parameterDesc = "";
  formData.alarmLevel = "";
  formData.typeCode = "";
  formData.typeId = "";
  formData.typeName = "";
  formData.relationId = "";
  formData.relationType = "";
  formData.sustainedTime = "0";
  formData.intervalTime = "0";
  formData.alarmContent = "";
  formData.enabled = 1;
  formData.isOrder = 1;
  formData.isMail = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.equipName = "";
  formData.processEquipCode = "";
}

const loading = ref(false);

/** 报警配置保存提交 */
function handleSubmit() {
  if (collectList.value.length == 0) {
    ElMessage.error("请先添加采集参数");
    return;
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      formData.relationId = route.query.id;
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/iotadmin/scaequipinfo/saveAlarm",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

const name = ref("");

async function getdetails() {
  let sondetails = await request({
    url: "/iotadmin/scaalarmsetting/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  equipTypeList.value?.forEach((item) => {
    if (item.id == formData.relationId) {
      name.value = `${item.equipTypeCode}-${item.equipTypeName}`;
    }
  });
}

const systypeList: any = ref([]);

async function getsystypeList() {
  let data = await request({
    url: "/system/sysmessagetype/getlist",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  systypeList.value = data.data;
}

function sysmesstypeChange(e: any) {
  let systypeitem = systypeList.value.find((item) => item.id === e);
  formData.typeName = systypeitem.typeName;
  formData.typeCode = systypeitem.typeCode;
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);
const getEquipTypeList = async () => {
  const res = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipTypeList.value = res.data;
    equipTypeList.value?.map((item) => {
      item.label = `${item.equipTypeCode}-${item.equipTypeName}`;
      item.value = `${item.equipTypeCode}`;
    });
  }
};
// 获取采集参数下拉框
const collectList: any = ref([]);
const getCollectList = async () => {
  const res = await request({
    url: `/iotadmin/scaequipinfo/get/${route.query.id}`,
    method: "get",
  });
  if (res.code === 200) {
    collectList.value = res.data.scaEquipCollectionParams;
  }
};
onMounted(() => {
  getEquipTypeList();
  getCollectList();
  getsystypeList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 600;
  color: #666;
  font-size: 15px;
  line-height: 15px;
  padding-top: 10px;
}

:deep(.el-dialog .el-dialog__body) {
  max-height: calc(100vh - 120px - 50px);
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}

.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-table .el-form-item) {
  padding: 10px 0 0 0 !important;
}
:deep(.el-form-item--default) {
  margin-bottom: 15px;
}

:deep(.formTable) {
  .el-table__body td.el-table__cell {
    padding: 0 !important;
  }
}

:deep(.el-table .el-form-item__error) {
  font-size: 11px !important;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 90px;
}
// :deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
//   min-width: 180px;
// }
:deep(.el-descriptions__cell) {
  padding: 12px;
}
</style>
